package net.pimpas.persistence.util;

import java.beans.BeanInfo;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;

import javax.persistence.Id;

import net.pimpas.util.reflection.ReflectionUtil;

public abstract class PersistenceUtil {
	
	public static Object getEntityIdValue( Object entity ) {
		Object value = findIdValueInEntityUsingPd(entity);
		if(value == null) value = findIdValueInEntityUsingField(entity);
		
		return value;
	}
	
	private static Object findIdValueInEntityUsingPd( Object object ) {
		BeanInfo bi = ReflectionUtil.instanceBeanInfo(object.getClass());
		
		for(PropertyDescriptor pd: bi.getPropertyDescriptors()) {
			if(pd.getReadMethod().getAnnotation(Id.class)!=null) {
				try {
					return pd.getReadMethod().invoke(object);
				} catch(Throwable t){
					return null;
				}
			}
		}
		return null;
	}
	
	private static Object findIdValueInEntityUsingField( Object object ) {
		for(Field field: object.getClass().getFields()) {
			if(field.getAnnotation(Id.class) != null)
				try {
					return field.get(object);
				} catch(Throwable t){
					return null;
				}
		}
		return null;
	}
}